import { ref } from "vue"
import { defineStore } from 'pinia'


export default defineStore('mainLinksStore', ()=>{
  
  // 最大链接数
  const maxCount = 15;//最大链接个数

  const index = ref(-1);//当前编辑中的ID

  const indexOperate = {
    isOk(_index){
      let b =  _index>=0 && _index<links.value.length;

      if(!b) {
        console.error('index err: ' + _index);
        return false;
      }
      return true;
    },
    set(_index){
      if(this.isOk(_index)){
        index.value = _index;
        return true;
      }
      return false;
    },
    reset:()=>index.value = -1,
  }


  // 链接数据
  const links = ref([
    {
      text:"搜狐",
      href:"https://www.sohu.com/",
      icon:"https://statics.itc.cn/web/static/images/pic/sohu-logo/favicon.ico",
    },
    {
      text:"今日头条",
      href:"https://video.eastday.com/",
      icon:"",
    },
    {
      text:"东方财富",
      href:"http://www.eastmoney.com/",
      icon:"",
    },
    {
      text:"中关村在线",
      href:"https://www.zol.com.cn",
      icon:"https://icon.zol-img.com.cn/favicon/180.png",
    },
    {
      text:"小红书",
      href:"https://www.xiaohongshu.com/",
      icon:"",
    },
    {
      text:"携程",
      href:"https://www.ctrip.com/",
      icon:"",
    },
    {
      text:"汽车之家",
      href:"http://car.autohome.com.cn/",
      icon:"",
    },
    {
      text:"虎扑",
      href:"http://bbs.hupu.com/",
      icon:"",
    },
    {
      text:"b站",
      href:"https://www.bilibili.com/",
      icon:"",
    },
    {
      text:"39健康",
      href:"https://www.39.net",
      icon:"",
    },

  ]);


  // 取值
  // function getRow(_index){

  //   if(_index<0 || _index>links.value.length) return;

  //   index.value = _index;//记录当前index
    
  //   return Object.assign({}, links.value[_index]);
  // }

  function getRow(){
    if(index.value<0 || index.value>links.value.length) return;
    return Object.assign({}, links.value[index.value]);
  }

  
  // 更新
  function save(row){

    if(index.value<0){
      // 新建
      links.value.push(Object.assign({}, row));
    }
    else{
      // 更改
      links.value[index.value] = Object.assign({}, row);
      index.value = -1;
    }
    
  }


  // 删除
  function del(){
    links.value.splice(index.value, 1);
  }


  return {links, index, indexOperate, maxCount, getRow, save, del};


}, {
  persist:{
    storage: localStorage,
    paths: ['links'],//必需与state一致
  }
});

